package com.example.capturetheflag.createGame;

import java.util.List;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.capturetheflag.R;
import com.example.capturetheflag.connection.HttpPostCreateAreaRequest;
import com.example.capturetheflag.helper.GameField;
import com.example.capturetheflag.helper.PlayerMarker;
import com.example.capturetheflag.helper.Singleton;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


public class CreateAreaActivity extends MapActivity implements LocationListener {
	
	private final int GAME_FIELD_SELECTED_CORNERS = 4;
	private static Boolean PLAYER_CENTER = false;
	private static Boolean FIELD_CENTER = false;
	
	public static int GlobalIdGry = 0;
	
	private MapView mapView;
	private GameField gameField;
	private PlayerMarker playerMarker;
	private MapController mapController;
	private Button bt;
	private List<Overlay> listaWarstw;
	private Boolean wasCentered, wasFieldLock, wasAreaCreated;
	private Dialog dialog;
	
	@Override
  public void onCreate(Bundle savedInstanceState) {
	        
      super.onCreate(savedInstanceState);
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      
      setContentView(R.layout.activity_create_area);

  	  bt = (Button)findViewById(R.id.setField);
      
      mapView = (MapView) findViewById(R.id.mapview);
      
      mapController = mapView.getController();
      
      listaWarstw = mapView.getOverlays();
      
      LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
      
      Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
      playerMarker = new PlayerMarker(drawable, this);
      
      listaWarstw.add(playerMarker);
      
      wasCentered = false;
      wasFieldLock = false;
      wasAreaCreated = false;
      mapView.setSatellite(false);  
      mapView.setTraffic(false);
      
      dialog = new Dialog(this);
      dialog.setTitle("Please Wait for GPS..");
      dialog.show();
      dialog.setCancelable(false);

      mapView.setClickable(false);
      
      setTitle("Create area - gameID: " + Singleton.getInstance().gameID);
  }
	
  @Override
	public boolean onCreateOptionsMenu(Menu menu) {
  	MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.layout.game_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
	        case R.id.zoomIn:
				mapView.getController().zoomIn();
	            return true;
	        case R.id.zoomOut:
				mapView.getController().zoomOut();
	            return true;
	        case R.id.menu:
				finish();
              return true;
          case R.id.satelite:
				mapView.setSatellite(true);
              return true;
          case R.id.map:
				mapView.setSatellite(false);
              return true;
          default:
              return super.onOptionsItemSelected(item);
      }
  }

	@Override
	public void onBackPressed() 
	{
		Toast.makeText(this, "To back to main screen or exit, go to settings and pres 'MENU'", Toast.LENGTH_SHORT).show();
	}
	
	public void myClickHandler (View target) {
		switch(target.getId()) {
			case R.id.setField:
				if(!wasFieldLock)
				{
			        gameField = new GameField(GAME_FIELD_SELECTED_CORNERS);
			        listaWarstw.add(gameField);
		        	bt.setText("<Save Points>");
			        wasFieldLock = true;
				}
				else
				{
					if(!mapView.isClickable())
					{
						if(!wasAreaCreated){
							String id_game = Singleton.getInstance().gameID;
							HttpPostCreateAreaRequest httpPostRequest1 = new HttpPostCreateAreaRequest();
							httpPostRequest1.execute("http://proinz.studentlive.pl/GeoService.svc/CreateArea" , "CreateArea"
									,id_game.toString() ,
									Integer.toString(gameField.fieldPoints.get(0).getLatitudeE6()),Integer.toString(gameField.fieldPoints.get(0).getLongitudeE6()),
								    Integer.toString(gameField.fieldPoints.get(1).getLatitudeE6()),Integer.toString(gameField.fieldPoints.get(1).getLongitudeE6()),
								    Integer.toString(gameField.fieldPoints.get(2).getLatitudeE6()),Integer.toString(gameField.fieldPoints.get(2).getLongitudeE6()),
								    Integer.toString(gameField.fieldPoints.get(3).getLatitudeE6()),Integer.toString(gameField.fieldPoints.get(3).getLongitudeE6()));
							Toast.makeText(this, "Game points saved on server", Toast.LENGTH_SHORT).show();
							bt.setText("Click to save");
							wasAreaCreated = true;
						}
						else if(!FIELD_CENTER)
						{
							mapController.animateTo(gameField.getCenterOfField());
				        	bt.setText("Go To Player");
				        	FIELD_CENTER = true;
							PLAYER_CENTER = false;
						}
						else
						{
							PLAYER_CENTER = true;
				        	FIELD_CENTER = false;
			        		bt.setText("Go To Field");
						}
					}
				}
				break;
	     } 
	}
  
  public void onLocationChanged(Location location) {
  	if(playerMarker.getmOverlays().size()>0)
  		playerMarker.getmOverlays().remove(0);
  	
  	if(dialog.isShowing())
  		dialog.dismiss();
  	
      Log.v("test", "location received ! "+location.getLatitude()+";"+location.getLongitude());
      
      GeoPoint me = new GeoPoint( (int)(location.getLatitude()*1000000), (int)(location.getLongitude()*1000000) );
      
          
      OverlayItem overlayitem = new OverlayItem(me, "To ty!", "8D");
      playerMarker.addOverlay(overlayitem);
      
      if(!wasCentered)
      {
      	mapController.setCenter(me);
      	wasCentered = true;
          mapController.setZoom(16);
          mapView.setClickable(true);
      }
      if(!mapView.isClickable())
      {
      	if(PLAYER_CENTER && !FIELD_CENTER)
          	mapController.animateTo(me);
      	else if(!FIELD_CENTER && !PLAYER_CENTER)
      		bt.setText("Click to save");
      	
      }
  }

  public void onProviderDisabled(String provider) {
      Log.v("test", "location provider disabled");

  }

  public void onProviderEnabled(String provider) {
      Log.v("test", "location provider enabled");

  }

  public void onStatusChanged(String provider, int status, Bundle extras) {
      Log.v("test", "location provider status changed");

  }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
   protected boolean isLocationDisplayed() {
       return false; 
   }

	@Override
  public void onDestroy()
  {
      super.onDestroy();
      finish();
  }
}
